<?php

class indexAction extends sfAction
{

  public function execute( $request )
  {
    // Don't escape output
    sfConfig::set( 'sf_escaping_strategy', false );
    // App may want to use different layout for this module
    // so we may have an overriding layout set in app.yml
    // TODO try to find out if we can use the view.yml
    $appLayout = sfConfig::get( 'app_essential_app_layout' );
    if ( $appLayout ) $this->setLayout( $appLayout );
    // Check if we've got the homepage or something else
    // and retrieve corresponding page object from database
    if ( !$request->hasParameter( 'slug' ) )
    {
      $page = Doctrine::getTable( 'EssentialPage' )->findOneByLevel( 0 );
    }
    else
    {
      $page = $this->getRoute()->getObject();
    }
    // Check whether the URL matches the routing
    $this->node = $page->getNode();
    $this->forward404If( !wgEssentialRouting::matches( $request->getPathInfo(), $this->node ) );
    // Retrieve page content
    $state = Doctrine_Query::create()
            ->from( 'EssentialPageState s' )
            ->where( 's.essential_page_id = ?', $page->getId() )
            ->andWhere( 's.published = ?', 1 )
            ->limit( 1 )->fetchOne();
    // Throw 404 error if no content exists
    $this->forward404If( !$state );
    // Make data available to the template
    $this->title = $page->getTitle();
    $this->body = $state->getBody();
  }

}